package com.hanbang.gycatering.homepage;

import java.util.ArrayList;
import java.util.Collection;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.hanbang.gangyu.R;
import com.hanbang.gycatering.aboutme.AboutMe;
import com.hanbang.gycatering.adpater.BannerAdAdapter;
import com.hanbang.gycatering.adpater.BannerAdAdapter.OnItemClickListener;
import com.hanbang.gycatering.application.MyApplication;
import com.hanbang.gycatering.bean.BannerAdData;
import com.hanbang.gycatering.bean.HomeItemContentData;
import com.hanbang.gycatering.bean.HomeItemData;
import com.hanbang.gycatering.classify.ClassifyActivity;
import com.hanbang.gycatering.classify.ClassifyList;
import com.hanbang.gycatering.classify.ProductDetail;
import com.hanbang.gycatering.myviews.ListViewForScrollView;
import com.hanbang.gycatering.property.PropertyService;
import com.hanbang.gycatering.shoppingcart.ShoppingCart;
import com.hanbang.gycatering.utils.HttpInterfaces;
import com.hanbang.gycatering.utils.JsonHelper;
import com.hanbang.gycatering.utils.MyLog;
import com.hanbang.gycatering.utils.MyRequestCallBack;
import com.hanbang.gycatering.utils.ShareMethod;
import com.hanbang.gycatering.utils.SystemTools;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

public class HomePageActivity extends MainBaseActivity {
	private ViewGroup ll_one, ll_two, ll_three, ll_four, ll_five;
	private ArrayList<BannerAdData> bannerAdDatas = new ArrayList<BannerAdData>();
	private BannerAdAdapter bannerAdAdapter = null;
	private PullToRefreshScrollView scrollView = null;
	private ListViewForScrollView listView = null;
	private ArrayList<HomeItemData> listData = new ArrayList<HomeItemData>();
	private MyAdapter listAdapter = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.homepageactivity);
		initView();
		setTheClick();
		getHomepageData();

	}

	private void initView() {
		((TextView) findViewById(R.id.top_bar_title)).setText("首页");
		ll_one = (ViewGroup) findViewById(R.id.bottom_bar_ll1);
		ll_two = (ViewGroup) findViewById(R.id.bottom_bar_ll2);
		ll_three = (ViewGroup) findViewById(R.id.bottom_bar_ll3);
		ll_four = (ViewGroup) findViewById(R.id.bottom_bar_ll4);
		ll_five = (ViewGroup) findViewById(R.id.bottom_bar_ll5);
		((ImageView) findViewById(R.id.top_bar_left_image))
				.setVisibility(View.GONE);
		scrollView = (PullToRefreshScrollView) findViewById(R.id.scrollview);
		scrollView.setMode(Mode.PULL_FROM_START);
		scrollView.setOnRefreshListener(new OnRefreshListener2<ScrollView>() {

			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<ScrollView> refreshView) {
				getHomepageData();
			}

			@Override
			public void onPullUpToRefresh(
					PullToRefreshBase<ScrollView> refreshView) {
			}

		});

		// 初始化广告条 数据完成的时候要调用start
		bannerAdAdapter = new BannerAdAdapter(this,
				(RelativeLayout) findViewById(R.id.banner_ad), bannerAdDatas);
		bannerAdAdapter.setWidthAndHeight(16, 9);
		bannerAdAdapter.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(View v, int position) {
				try {
					Intent intent = new Intent(HomePageActivity.this,
							ProductDetail.class);
					intent.putExtra("id", bannerAdDatas.get(position).getId());
					startActivity(intent);

				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		});

		listView = (ListViewForScrollView) findViewById(R.id.listView);
		listAdapter = new MyAdapter();
		listView.setAdapter(listAdapter);

	}

	private void setTheClick() {
		ll_one.setOnClickListener(myOncClickListener);
		ll_two.setOnClickListener(myOncClickListener);
		ll_three.setOnClickListener(myOncClickListener);
		ll_four.setOnClickListener(myOncClickListener);
		ll_five.setOnClickListener(myOncClickListener);
	}

	// 底部导航监听
	private OnClickListener myOncClickListener = new OnClickListener() {
		@Override
		public void onClick(View view) {
			Intent intent = new Intent();
			switch (view.getId()) {
			case R.id.bottom_bar_ll2:
				intent.setClass(HomePageActivity.this, ClassifyActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
				startActivity(intent);
				break;
			case R.id.bottom_bar_ll3:
				intent.setClass(HomePageActivity.this, PropertyService.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
				startActivity(intent);
				break;
			case R.id.bottom_bar_ll4:
				intent.setClass(HomePageActivity.this, ShoppingCart.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
				startActivity(intent);
				break;
			case R.id.bottom_bar_ll5:
				intent.setClass(HomePageActivity.this, AboutMe.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
				startActivity(intent);
				break;

			default:
				break;
			}
		}
	};

	private void getHomepageData() {
		((MyApplication) getApplicationContext()).httpUtils.send(
				HttpMethod.GET, HttpInterfaces.homepage,
				new MyRequestCallBack<String>(HomePageActivity.this,
						getString(R.string.loadding)) {
					@Override
					public void onFailure(HttpException error, String msg) {
						super.onFailure(error, msg);
						scrollView.onRefreshComplete();
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						super.onSuccess(responseInfo);
						try {
							JSONObject json = new JSONObject(
									responseInfo.result);
							if (json.getInt("state") == 1) {
								bannerAdDatas.clear();
								listData.clear();

								// 解析顶部数据
								JSONObject info = json.getJSONObject("info");
								JSONArray top = info.getJSONArray("top");
								changeTopUi(top);

								Collection<HomeItemData> dataS = JsonHelper
										.parseCollection(
												info.getJSONArray("list"),
												ArrayList.class,
												HomeItemData.class);
								listData.addAll(dataS);
								// // 解析今日特价
								// JSONArray sale = info.getJSONObject(1)
								// .getJSONArray("sale");
								// changeOtherUi(sale, findViewById(R.id.tab1),
								// 0,
								// "今日特价");
								// // 解析每周精选
								// JSONArray auslese = info.getJSONObject(2)
								// .getJSONArray("auslese");
								// changeOtherUi(auslese,
								// findViewById(R.id.tab2),
								// 1, "每周精选");
								// // 解析手快有 手慢无
								// JSONArray quick = info.getJSONObject(3)
								// .getJSONArray("quick");
								// changeOtherUi(quick, findViewById(R.id.tab3),
								// 2, "手快有手慢无");
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
						listAdapter.notifyDataSetChanged();
						scrollView.onRefreshComplete();
					}
				});
	}

	/*
	 * TOP json解析 改变ui
	 */
	private void changeTopUi(JSONArray top) throws JSONException {
		for (int i = 0; i < top.length(); i++) {
			JSONObject item = top.getJSONObject(i);
			BannerAdData data = new BannerAdData();
			data.setId(item.getInt("id"));
			data.setPath(item.getString("img"));
			bannerAdDatas.add(data);
		}
		bannerAdAdapter.notifyDataSetChanged();
		bannerAdAdapter.start();
	}

	private class MyAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return listData.size();
		}

		@Override
		public Object getItem(int position) {
			return listData.get(position);
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@SuppressLint("InflateParams")
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder viewHolder = null;
			if (convertView == null) {
				convertView = getLayoutInflater().inflate(
						R.layout.home_list_item, null);
				viewHolder = findView(convertView);
				convertView.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}
			changeOtherUi(position, viewHolder);
			return convertView;
		}

		/*
		 * HomeItemData
		 */
		private void changeOtherUi(int position, ViewHolder viewHolder) {
			final HomeItemData data = listData.get(position);
			viewHolder.title.setText(data.getTypename());
			viewHolder.titleLinear.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(HomePageActivity.this,
							ClassifyList.class);
					intent.putExtra("id", data.getTypeid());
					intent.putExtra("httpBase", HttpInterfaces.pagemore);
					intent.putExtra("title", data.getTypename());
					startActivity(intent);
				}
			});

			if (data.getContent() != null) {
				try {
					if (position % 2 == 0) {
						changeOneItemUi(data.getContent().get(0),
								viewHolder.item1);
						viewHolder.item1.line.setVisibility(View.VISIBLE);
						viewHolder.item1_2.line.setVisibility(View.GONE);
					} else {
						changeOneItemUi(data.getContent().get(0),
								viewHolder.item1_2);
						viewHolder.item1_2.line.setVisibility(View.VISIBLE);
						viewHolder.item1.line.setVisibility(View.GONE);
					}
					viewHolder.item2.line.setVisibility(View.GONE);
					changeOneItemUi(data.getContent().get(1), viewHolder.item2);
					viewHolder.item3.line.setVisibility(View.GONE);
					changeOneItemUi(data.getContent().get(2), viewHolder.item3);
					viewHolder.item4.line.setVisibility(View.GONE);
					changeOneItemUi(data.getContent().get(3), viewHolder.item4);
				} catch (IndexOutOfBoundsException e) {
					e.printStackTrace();
				}
			} else {
				viewHolder.item1.line.setVisibility(View.GONE);
				viewHolder.item1_2.line.setVisibility(View.GONE);
				viewHolder.item2.line.setVisibility(View.GONE);
				viewHolder.item3.line.setVisibility(View.GONE);
				viewHolder.item4.line.setVisibility(View.GONE);
			}

		}

		/*
		 * HomeItemContentData
		 */
		private void changeOneItemUi(final HomeItemContentData item,
				ViewHolderChild child) {
			String uri = item.getImg();
			if (uri.startsWith("http://")) {
				bitmapUtils.display(child.imageView, uri);
			} else {
				bitmapUtils.display(child.imageView, HttpInterfaces.ORG + uri);
			}
			child.name.setText(item.getName());
			child.price.setText("¥"
					+ SystemTools.roundString(item.getPrice(), 2));

			child.line.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent intent = new Intent(HomePageActivity.this,
							ProductDetail.class);
					intent.putExtra("id", item.getId());
					startActivity(intent);

				}
			});
			child.line.setVisibility(View.VISIBLE);
		}

		/*
		 * 查找控件
		 */
		private ViewHolder findView(View view) {
			ViewHolder viewHolder = new ViewHolder();
			ViewHolderChild child = new ViewHolderChild();
			child.imageView = (ImageView) view.findViewById(R.id.img1);
			child.name = (TextView) view.findViewById(R.id.name1);
			child.price = (TextView) view.findViewById(R.id.price1);
			child.line = (LinearLayout) view.findViewById(R.id.item1_1);
			viewHolder.item1 = child;

			child = new ViewHolderChild();
			child.imageView = (ImageView) view.findViewById(R.id.img1_2);
			child.name = (TextView) view.findViewById(R.id.name1_2);
			child.price = (TextView) view.findViewById(R.id.price1_2);
			child.line = (LinearLayout) view.findViewById(R.id.item1_2);
			viewHolder.item1_2 = child;

			child = new ViewHolderChild();
			child.imageView = (ImageView) view.findViewById(R.id.img2);
			child.name = (TextView) view.findViewById(R.id.name2);
			child.price = (TextView) view.findViewById(R.id.price2);
			child.line = (LinearLayout) view.findViewById(R.id.item2);
			viewHolder.item2 = child;

			child = new ViewHolderChild();
			child.imageView = (ImageView) view.findViewById(R.id.img3);
			child.name = (TextView) view.findViewById(R.id.name3);
			child.price = (TextView) view.findViewById(R.id.price3);
			child.line = (LinearLayout) view.findViewById(R.id.item3);
			viewHolder.item3 = child;

			child = new ViewHolderChild();
			child.imageView = (ImageView) view.findViewById(R.id.img4);
			child.name = (TextView) view.findViewById(R.id.name4);
			child.price = (TextView) view.findViewById(R.id.price4);
			child.line = (LinearLayout) view.findViewById(R.id.item4);
			viewHolder.item4 = child;

			viewHolder.title = (TextView) view.findViewById(R.id.title);

			viewHolder.titleLinear = (LinearLayout) view
					.findViewById(R.id.title_ll);

			return viewHolder;

		}

	}

	static class ViewHolderChild {
		LinearLayout line = null;

		ImageView imageView = null;
		TextView name = null;
		TextView price = null;
	}

	static class ViewHolder {
		ViewHolderChild item1;
		ViewHolderChild item1_2;
		ViewHolderChild item2;
		ViewHolderChild item3;
		ViewHolderChild item4;

		TextView title = null;
		LinearLayout titleLinear = null;

	}

	@Override
	protected void onResume() {
		super.onResume();
		ShareMethod.setButton(ll_one, false);

	};

	@Override
	protected void onPause() {
		super.onPause();
		ShareMethod.setButton(ll_one, true);
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

}
